﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcDaManagerEnglish : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session[SessionConst.SES_DA_MANAGEMENT_GRVDATA] = null;
                LoadGrvData();
            }
            else
            {
                grvData.DataSource = Session[SessionConst.SES_DA_MANAGEMENT_GRVDATA];
            }
        }
        protected void LoadCbbStatus()
        {
            var cbb = grvData.Columns["Status"] as GridViewDataComboBoxColumn;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(Int32);
            cbb.PropertiesComboBox.Items.Add("Running", Common.ProjectRunning);
            cbb.PropertiesComboBox.Items.Add("Pause", Common.ProjectPause);
            cbb.PropertiesComboBox.Items.Add("Finished", Common.ProjectFinished);
        }
        protected void LoadGrvData()
        {
            LoadCbbStatus();
            var cu = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var data = (from d in DaoHelper.Entities.PhanQuyenDuAns
                        join s in DaoHelper.Entities.DuAns on d.MaDuAn equals s.MaDuAn
                        where (d.UserName.Equals(cu) )
                        select s).ToList();
            var dt = new DataTable();
            dt.Columns.Add("MaDuAn", typeof(int));
            dt.Columns.Add("TenDuAn", typeof(string));
            dt.Columns.Add("ChuThich", typeof(string));
            dt.Columns.Add("DiaDiem", typeof(string));
            dt.Columns.Add("Display", typeof (string));
            dt.Columns.Add("Edit", typeof (string));
            dt.Columns.Add("HangMucQuanTrac", typeof (string));
            dt.Columns.Add("Longitude", typeof (string));
            dt.Columns.Add("Latitude", typeof(string));
            dt.Columns.Add("Altitude", typeof(string));
            dt.Columns.Add("Status", typeof(int));
            foreach (var d in data)
            {
                var dr = dt.NewRow();
                dr["MaDuAn"] = d.MaDuAn;
                dr["TenDuAn"] = d.TenDuAn;
                dr["ChuThich"] = d.ChuThich;
                dr["DiaDiem"] = d.DiaDiem;
                dr["HangMucQuanTrac"] = d.HangMucQuanTrac;
                dr["Display"] = "";
                dr["Edit"] = "";
                dr["Altitude"] = d.Altitude;
                dr["Latitude"] = d.Latitude;
                dr["Longitude"] = d.Longitude;
                dr["Status"] = d.Status;
                var pq = (from e in DaoHelper.Entities.PhanQuyenDuAns where e.MaDuAn == d.MaDuAn select e).ToList();
                foreach (var phanQuyenDuAn in pq)
                {
                    if (phanQuyenDuAn.Role.Equals(Common.R_W_D))
                        dr["Edit"] += phanQuyenDuAn.UserName + ",";
                    else
                    {
                        dr["Display"] += phanQuyenDuAn.UserName + ",";
                    }
                }

                dt.Rows.Add(dr);
            }


            Session[SessionConst.SES_DA_MANAGEMENT_GRVDATA] = dt;
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void Msg()
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "alert1", "<script type='text/javascript'>alert('You have not permission to edit')</script>", false);
        }

        protected bool CanEdit(int maDa)
        {
            string user = ((SessionUser)(Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            var tb = (from p in DaoHelper.Entities.PhanQuyenDuAns
                      where (p.UserName.Equals(user) && p.MaDuAn.Equals(maDa) && p.Role.Equals(Common.R_W_D))
                      select p).ToList();
            if (tb.Count > 0)
                return true;
            return false;
        }

        protected void grvData_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            int maDa = Convert.ToInt32(e.Values["MaDuAn"]);
            if (CanEdit(maDa))
            {
                try
                {
                    var a = DaoHelper.Entities.DuAns
                        .FirstOrDefault(p => p.MaDuAn==maDa);
                    if (a != null)
                    {
                        DaoHelper.Entities.DuAns.Remove(a);
                        DaoHelper.Entities.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Delete unsuccessfull, please try again.");
                }
            }
            else
            {
                throw new ArgumentException("You have not permission to edit information");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }

        protected string AddQuyenNsd(int duan,string nsd, string quyen)
        {
            string rs = string.Empty;
            if (string.IsNullOrEmpty(nsd)) return rs;

            nsd = nsd.TrimEnd(',');
            string[] str = nsd.Split(',');
            rs = str.Where(s => DaoHelper.Entities.NguoiSuDungs.FirstOrDefault(p => p.UserName == s) == null)
                .Aggregate(rs, (current, s) => current + (s + ","));

            if (!string.IsNullOrEmpty(rs))
                return rs.TrimEnd(',');

            foreach (string s in str)
            {
                if(string.IsNullOrEmpty(s))
                    continue;
                
                var e = (from d in DaoHelper.Entities.PhanQuyenDuAns where (d.MaDuAn == duan &&d.UserName==s)select d).ToList();
                if (e.Count == 0)
                {
                    var pq = new PhanQuyenDuAn();
                    pq.MaDuAn = duan;
                    pq.Role = quyen;
                    pq.UserName = s;
                    DaoHelper.Entities.PhanQuyenDuAns.Add(pq);
                }
                else
                {
                    e[0].Role = quyen;
                }

                DaoHelper.Entities.SaveChanges();
            }
            return rs;
        }

        protected void grvData_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            try
            {

                var tenDa =(string) e.NewValues["TenDuAn"];
                var chuthich =(string) e.NewValues["ChuThich"];
                var diadiem = (string) e.NewValues["DiaDiem"];
                var hangMucQuanTrac = (string) e.NewValues["HangMucQuanTrac"];
                var iso = new DuAn();
                iso.TenDuAn = tenDa;
                iso.ChuThich = chuthich;
                iso.DiaDiem = diadiem;
                iso.HangMucQuanTrac = hangMucQuanTrac;
                iso.Latitude = (string)e.NewValues["Latitude"];
                iso.Longitude = (string)e.NewValues["Longitude"];
                iso.Altitude = (string)e.NewValues["Altitude"];
                iso.Status = Convert.ToInt32(e.NewValues["Status"]);
                DaoHelper.Entities.DuAns.Add(iso);
                DaoHelper.Entities.SaveChanges();

                var pq = new PhanQuyenDuAn();
                pq.MaDuAn = iso.MaDuAn;
                pq.UserName = ((SessionUser)(Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
                pq.Role = Common.R_W_D;
                DaoHelper.Entities.PhanQuyenDuAns.Add(pq);

                DaoHelper.Entities.SaveChanges();

                string str=AddQuyenNsd(iso.MaDuAn, (string) e.NewValues["Display"], Common.R);
                if(!string.IsNullOrEmpty(str)) throw new ArgumentException("Danh sách người được xem thông tin: Người sử dụng '"+str+"' không tồn tại");

                str = AddQuyenNsd(iso.MaDuAn, (string)e.NewValues["Edit"], Common.R_W_D);
                if (!string.IsNullOrEmpty(str)) throw new ArgumentException("Danh sách người được điều chỉnh thông tin: Người sử dụng '" + str + "' không tồn tại");

            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception)
            {

                throw new Exception("Add unsuccessfull, please try again.");
            }
           
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }
        protected void DeleteDataByDa(int maDA)
        {
            try
            {

                var vSensorTest = (from v in DaoHelper.Entities.SensorValuesTests
                                   where (v.MaDuAn == maDA)
                                   select v).ToList();
                DaoHelper.Entities.SensorValuesTests.RemoveRange(vSensorTest);

                var vSensor1000 = (from v in DaoHelper.Entities.SensorValues1000
                                   where (v.MaDuAn == maDA)
                                   select v).ToList();
                DaoHelper.Entities.SensorValues1000.RemoveRange(vSensor1000);

                var vSensorLatest = (from v in DaoHelper.Entities.SensorLatestValues
                                     where (v.MaDuAn == maDA)
                                     select v).ToList();
                DaoHelper.Entities.SensorLatestValues.RemoveRange(vSensorLatest);
                //DaoHelper.Entities.SaveChanges();
                //return 1;

            }
            catch (Exception)
            {

                //return -1;
            }
        }
        protected void grvData_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            int maDa=Convert.ToInt32(e.NewValues["MaDuAn"]);
            if (CanEdit(maDa))
            {
                try
                {
                    var iso = DaoHelper.Entities.DuAns.FirstOrDefault(p => p.MaDuAn == maDa);
                    if (iso != null)
                    {
                        //if (Convert.ToInt32(e.NewValues["Status"]) == 2) //if project finished delete all data of project
                        //    DeleteDataByDa(maDa);
                        iso.TenDuAn = (string) e.NewValues["TenDuAn"];
                        iso.ChuThich = (string) e.NewValues["ChuThich"];
                        iso.DiaDiem = (string) e.NewValues["DiaDiem"];
                        iso.HangMucQuanTrac = (string) e.NewValues["HangMucQuanTrac"];
                        iso.Latitude = (string)e.NewValues["Latitude"];
                        iso.Longitude = (string)e.NewValues["Longitude"];
                        iso.Altitude = (string)e.NewValues["Altitude"];
                        iso.Status = Convert.ToInt32(e.NewValues["Status"]);

                        var list = (from s in DaoHelper.Entities.Sensors
                                    join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                                    join q in DaoHelper.Entities.PhanQuyenDuAns on t.MaDuAn equals q.MaDuAn
                                    join a in DaoHelper.Entities.DuAns on q.MaDuAn equals a.MaDuAn

                                    where (a.MaDuAn == iso.MaDuAn && t.Status == 0)
                                    select s).ToList();
                        foreach (var sensor in list)
                        {
                            sensor.Latitude = iso.Latitude;
                            sensor.Longitude = iso.Longitude;
                        }

                        DaoHelper.Entities.SaveChanges();
                        string str = AddQuyenNsd(iso.MaDuAn, (string)e.NewValues["Display"], Common.R);
                        if (!string.IsNullOrEmpty(str)) throw new ArgumentException("Danh sách người được xem thông tin: Người sử dụng '" + str + "' không tồn tại");

                        str = AddQuyenNsd(iso.MaDuAn, (string)e.NewValues["Edit"], Common.R_W_D);
                        if (!string.IsNullOrEmpty(str)) throw new ArgumentException("Danh sách người được điều chỉnh thông tin: Người sử dụng '" + str + "' không tồn tại");
                    }
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Update unsuccessfull, please try again.");
                }
            }
            else
            {
                throw new ArgumentException("You have not permission to edit information");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }


    }
}